import {Box,Diamond,Money,Star} from './Son.js'
class Girl{
  constructor(ele){
    this.img = document.createElement('img')
    this.img.src = 'imgs/girl.gif'
    this.img.id = 'girl'
    this.left = 360
    this.img.style.left = this.left + 'px'
    ele.appendChild(this.img)
  }
  goLeft(){
    this.left-=20;//小女孩向左边走
    if(this.left<0)
       this.left=720;
    this.img.style.left=this.left+"px";
    this.img.classList.remove("goright");
  }
  goRight(){
    this.left+=20;
    if(this.left>720)
       this.left=0;
    this.img.style.left=this.left+"px";
    this.img.classList.add("goright");
  }
}


let main=document.getElementById("main");
// let girl = document.getElementById("girl");
let girl = new Girl(main)
let startBtn=document.getElementById("startBtn");
let audio=document.getElementById("audio");

// let girl_left=360;
let timer=null;

let babyAry=[];
for(let i=0;i<3;i++)
babyAry.push(new Star(parseInt(Math.random()*720),0,parseInt(Math.random()*30)+10,600,main));
for(let i=0;i<2;i++)
babyAry.push(new Money(parseInt(Math.random()*720),0,parseInt(Math.random()*10)+10,600,main,200));
for(let i=0;i<2;i++)
babyAry.push(new Diamond(parseInt(Math.random()*720),0,parseInt(Math.random()*30)+10,600,main));
for(let i=0;i<2;i++)
babyAry.push(new Box(parseInt(Math.random()*720),0,parseInt(Math.random()*30)+10,500,main));

//为每个star对象设置钩子方法，当跌出地面的时候，当发生碰撞的时候
babyAry.forEach(baby=>{
  baby.xxFun=function(){
      score-=1;
      bd2.style.width=score+"%";
      if(score<=0){
          window.clearInterval(timer);
          alert("GAME OVER");
          return;
      }
  };
  baby.toutchFun=function(){
      main.classList.add("c");
      audio.play();
      //加分
      score+=5;
      if(score>100)
          score=100;
      bd2.style.width=score+"%";   
  }
})


function startGame(){
if(timer==null){
   timer= window.setInterval(move,100);
   startBtn.innerHTML="PUSH";
}
else{
   window.clearInterval(timer);
   timer=null;
   startBtn.innerHTML="CONTINUE";
}
}

let score=50;
function move(){
 babyAry.forEach(star=>{
    star.move();//星星向下移动
    star.isToutch(girl.img);//每次移动都判断一下是否碰到对方
 })
}
main.addEventListener("animationend",function(){
  console.log(this);
  this.classList.remove("c")
});
document.onkeydown=function(e){
  switch(e.keyCode){
      case 37: //left
          girl.goLeft()
          break;
      case 39:
          girl.goRight()
      default:
          break;

  }
}
window.startGame = startGame